<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.1">
  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16.png">
  <link rel="mask-icon" href="/blog/images/logo.svg" color="#222">

<link rel="stylesheet" href="/blog/css/main.css">


<link rel="stylesheet" href="/blog/lib/font-awesome/css/all.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"gitee.com","root":"/blog/","scheme":"Muse","version":"8.0.0-rc.4","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":true,"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":true,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}};
  </script>

  <meta name="description" content="分析Q&amp;AQ: 链表的基本单位是啥? A: 是结点(Node) Q: 结点是怎样构成的? A: 结点由2部分构成, 数据(data)和指向下一个结点的指针(next) Q: 链表中特殊的结点是啥? A: 是头结点(head), 作为起始结点, 没有头结点则为空链表(线性表允许有0个元素)">
<meta property="og:type" content="article">
<meta property="og:title" content="Python单链表">
<meta property="og:url" content="https://gitee.com/indoorsman_lab/blog/2020/07/02/Python%E5%8D%95%E9%93%BE%E8%A1%A8/index.html">
<meta property="og:site_name" content="宅人类研究室">
<meta property="og:description" content="分析Q&amp;AQ: 链表的基本单位是啥? A: 是结点(Node) Q: 结点是怎样构成的? A: 结点由2部分构成, 数据(data)和指向下一个结点的指针(next) Q: 链表中特殊的结点是啥? A: 是头结点(head), 作为起始结点, 没有头结点则为空链表(线性表允许有0个元素)">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2020-07-02T12:55:47.000Z">
<meta property="article:modified_time" content="2020-07-03T02:10:36.053Z">
<meta property="article:author" content="张雪峰">
<meta property="article:tag" content="链表">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="https://gitee.com/indoorsman_lab/blog/2020/07/02/Python%E5%8D%95%E9%93%BE%E8%A1%A8/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>Python单链表 | 宅人类研究室</title>
  






  <noscript>
  <style>
  body { margin-top: 2rem; }

  .use-motion .header,
  .use-motion .site-brand-container .toggle,
  .use-motion .menu-item,
  .use-motion .sidebar,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header,
  .use-motion .footer { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle,
  .use-motion .custom-logo-image {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line {
    transform: scaleX(1);
  }

  .search-pop-overlay, .sidebar-nav { display: none; }
  .sidebar-panel { display: block; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <main class="main">
      <header class="header" itemscope itemtype="http://schema.org/WPHeader">
        <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
        <span class="toggle-line toggle-line-first"></span>
        <span class="toggle-line toggle-line-middle"></span>
        <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/blog/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">宅人类研究室</h1>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">IndoorsMan Lab</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/blog/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/blog/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/blog/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/blog/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/blog/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
  </ul>
</nav>




</div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <section class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#分析Q-amp-A"><span class="nav-number">1.</span> <span class="nav-text">分析Q&amp;A</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#拆解代码"><span class="nav-number">2.</span> <span class="nav-text">拆解代码</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-首先定义结点"><span class="nav-number">2.1.</span> <span class="nav-text">1. 首先定义结点</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-定义单向链表"><span class="nav-number">2.2.</span> <span class="nav-text">2. 定义单向链表</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#2-1-初始化-init"><span class="nav-number">2.2.1.</span> <span class="nav-text">2.1 初始化__init__</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-2-添加-追加新结点-链表的新增"><span class="nav-number">2.2.2.</span> <span class="nav-text">2.2 添加&#x2F;追加新结点(链表的新增)</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-3-判断链表是否为空"><span class="nav-number">2.2.3.</span> <span class="nav-text">2.3 判断链表是否为空</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-4-获取链表的长度"><span class="nav-number">2.2.4.</span> <span class="nav-text">2.4 获取链表的长度</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-5-在任意位置插入结点"><span class="nav-number">2.2.5.</span> <span class="nav-text">2.5 在任意位置插入结点</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-6-删除结点"><span class="nav-number">2.2.6.</span> <span class="nav-text">2.6 删除结点</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-7-打印链表"><span class="nav-number">2.2.7.</span> <span class="nav-text">2.7 打印链表</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-8-倒置链表"><span class="nav-number">2.2.8.</span> <span class="nav-text">2.8 倒置链表</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-9-把列表-顺序表-转换成链表"><span class="nav-number">2.2.9.</span> <span class="nav-text">2.9 把列表(顺序表)转换成链表</span></a></li></ol></li></ol></li></ol></div>
      </section>
      <!--/noindex-->

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="张雪峰"
      src="/blog/images/avatar.jpg">
  <p class="site-author-name" itemprop="name">张雪峰</p>
  <div class="site-description" itemprop="description">IndoorsMan Lab</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/blog/archives/">
        
          <span class="site-state-item-count">15</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/blog/categories/">
          
        <span class="site-state-item-count">5</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/blog/tags/">
          
        <span class="site-state-item-count">12</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/indoorsmanlab" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;indoorsmanlab" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://gitee.com/indoorsman_lab" title="Gitee → https:&#x2F;&#x2F;gitee.com&#x2F;indoorsman_lab"><i class="fab fa-git-square fa-fw"></i>Gitee</a>
      </span>
  </div>


  <div class="links-of-blogroll motion-element">
    <div class="links-of-blogroll-title"><i class="fa fa-globe fa-fw"></i>
      Links
    </div>
    <ul class="links-of-blogroll-list">
        <li class="links-of-blogroll-item">
          <a href="https://blog.csdn.net/m0_46238775" title="https:&#x2F;&#x2F;blog.csdn.net&#x2F;m0_46238775" rel="noopener" target="_blank">宅人类研究室-CSDN</a>
        </li>
    </ul>
  </div>

      </section>
    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </header>

      
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

  <a href="https://github.com/indoorsmanlab" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>

<noscript>
  <div id="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


      <div class="main-inner">
        

        <div class="content post posts-expand">
          

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://gitee.com/indoorsman_lab/blog/2020/07/02/Python%E5%8D%95%E9%93%BE%E8%A1%A8/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/blog/images/avatar.jpg">
      <meta itemprop="name" content="张雪峰">
      <meta itemprop="description" content="IndoorsMan Lab">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="宅人类研究室">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Python单链表
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2020-07-02 20:55:47" itemprop="dateCreated datePublished" datetime="2020-07-02T20:55:47+08:00">2020-07-02</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2020-07-03 10:10:36" itemprop="dateModified" datetime="2020-07-03T10:10:36+08:00">2020-07-03</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%B8%8E%E7%AE%97%E6%B3%95/" itemprop="url" rel="index"><span itemprop="name">数据结构与算法</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h2 id="分析Q-amp-A"><a href="#分析Q-amp-A" class="headerlink" title="分析Q&amp;A"></a>分析Q&amp;A</h2><p>Q: 链表的基本单位是啥?</p>
<p>A: 是结点(Node)</p>
<p>Q: 结点是怎样构成的?</p>
<p>A: 结点由2部分构成, 数据(data)和指向下一个结点的指针(next)</p>
<p>Q: 链表中特殊的结点是啥?</p>
<p>A: 是头结点(head), 作为起始结点, 没有头结点则为空链表(线性表允许有0个元素)</p>
<a id="more"></a>

<h2 id="拆解代码"><a href="#拆解代码" class="headerlink" title="拆解代码"></a>拆解代码</h2><h3 id="1-首先定义结点"><a href="#1-首先定义结点" class="headerlink" title="1. 首先定义结点"></a>1. 首先定义结点</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 链表的基本单位--结点</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Node</span><span class="params">(object)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, data)</span>:</span></span><br><span class="line">        self.data = data  <span class="comment"># 结点的元素值</span></span><br><span class="line">        self.next = <span class="literal">None</span>  <span class="comment"># 表示下一个结点的链接</span></span><br></pre></td></tr></table></figure>
<h3 id="2-定义单向链表"><a href="#2-定义单向链表" class="headerlink" title="2. 定义单向链表"></a>2. 定义单向链表</h3><h4 id="2-1-初始化-init"><a href="#2-1-初始化-init" class="headerlink" title="2.1 初始化__init__"></a>2.1 初始化__init__</h4><p>作为判断是否为空链表的依据, 必须把头结点定义出来, 可以给个缺省参数None</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 链表</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">LinkedList</span><span class="params">(object)</span>:</span></span><br><span class="line">    <span class="comment"># 初始化链表</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, head=None)</span>:</span></span><br><span class="line">        self.head = head  <span class="comment"># 链表的头结点</span></span><br></pre></td></tr></table></figure>
<h4 id="2-2-添加-追加新结点-链表的新增"><a href="#2-2-添加-追加新结点-链表的新增" class="headerlink" title="2.2 添加/追加新结点(链表的新增)"></a>2.2 添加/追加新结点(链表的新增)</h4><ul>
<li>首先把游标指向头结点, 如果头结点不存在, 那就把新插入的结点设置为头结点;<br></li>
<li>如果头结点存在, 但是next指针指向None, 也就是说链表有且仅有头结点1个结点, 那么直接把next指针指向新结点即可; <br></li>
<li>如果头结点存在, 而且next指针指向了下一个结点, 那么把游标移动到下一个结点处, 直到游标所在的结点是链表的尾部结点(next–&gt;None), 把尾部结点的next指向新结点</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 追加新结点</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">append</span><span class="params">(self, new_element)</span>:</span></span><br><span class="line">    <span class="string">"""在链表的尾部追加新的元素"""</span></span><br><span class="line">    <span class="comment"># 首先把头结点设为当前结点</span></span><br><span class="line">    current = self.head</span><br><span class="line">    <span class="comment"># 如果头结点存在</span></span><br><span class="line">    <span class="keyword">if</span> self.head:</span><br><span class="line">        <span class="comment"># 如果头结点有链接</span></span><br><span class="line">        <span class="keyword">while</span> current.next:</span><br><span class="line">            <span class="comment"># 把链接的结点设置为当前结点, 继续循环</span></span><br><span class="line">            <span class="comment"># 直到当前结点为链表的最后一个结点</span></span><br><span class="line">            current = current.next</span><br><span class="line">        <span class="comment"># 头结点没有链接, 新元素作为头结点的链接</span></span><br><span class="line">        current.next = new_element</span><br><span class="line">    <span class="comment"># 如果头结点不存在</span></span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        <span class="comment"># 把新结点设置为头结点</span></span><br><span class="line">        self.head = new_element</span><br></pre></td></tr></table></figure>
<h4 id="2-3-判断链表是否为空"><a href="#2-3-判断链表是否为空" class="headerlink" title="2.3 判断链表是否为空"></a>2.3 判断链表是否为空</h4><p>很简单, 只需要判断头结点是否存在即可</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 判断链表是否为空链表</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">is_empty</span><span class="params">(self)</span>:</span></span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">not</span> self.head</span><br></pre></td></tr></table></figure>
<h4 id="2-4-获取链表的长度"><a href="#2-4-获取链表的长度" class="headerlink" title="2.4 获取链表的长度"></a>2.4 获取链表的长度</h4><p>先定义一个游标, 指向头结点, 初始化长度为0, 如果游标所在结点存在, 那么长度+1, 游标指向下一个结点, 直到游标指向None, 说明到了尾部结点, 此时已累加的长度就是链表长度</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 获取链表长度</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">get_length</span><span class="params">(self)</span>:</span></span><br><span class="line">    temp = self.head</span><br><span class="line">    length = <span class="number">0</span></span><br><span class="line">    <span class="comment"># 循环到尾部结点,next=None</span></span><br><span class="line">    <span class="keyword">while</span> temp <span class="keyword">is</span> <span class="keyword">not</span> <span class="literal">None</span>:</span><br><span class="line">        length = length + <span class="number">1</span></span><br><span class="line">        temp = temp.next</span><br><span class="line">    <span class="keyword">return</span> length</span><br></pre></td></tr></table></figure>
<h4 id="2-5-在任意位置插入结点"><a href="#2-5-在任意位置插入结点" class="headerlink" title="2.5 在任意位置插入结点"></a>2.5 在任意位置插入结点</h4><ul>
<li>首先考虑的是下标越界的问题, 下标小于0或大于链表长度时, 下标越界; 解释一下为啥不是长度-1呢? 因为任意位置也包括最后, 那么position自然是尾结点链表+1, 也就是长度的数值;<br></li>
<li>如果插入位置是0, 相当于把新结点的next指向老的头结点, 同时把新结点设置为新的头结点;<br></li>
<li>在其他位置插入的话, 从head开始遍历到指定位置前一个位置, 并把前一位置的next指向新结点, 同时把新结点的next指向原来在该位置上的结点, 完成插入</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 插入结点</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">insert</span><span class="params">(self, position, new_element)</span>:</span></span><br><span class="line">    <span class="string">"""在链表的指定索引处插入元素"""</span></span><br><span class="line">    <span class="comment"># 判断下标是否越界</span></span><br><span class="line">    <span class="keyword">if</span> position &lt; <span class="number">0</span> <span class="keyword">or</span> position &gt; self.get_length():</span><br><span class="line">        <span class="keyword">raise</span> IndexError(<span class="string">"插入操作超出索引范围"</span>)</span><br><span class="line">    temp = self.head</span><br><span class="line">    <span class="comment"># 在头结点处插入</span></span><br><span class="line">    <span class="keyword">if</span> position == <span class="number">0</span>:</span><br><span class="line">        new_element.next = temp</span><br><span class="line">        self.head = new_element</span><br><span class="line">        <span class="keyword">return</span></span><br><span class="line">    <span class="comment"># 找到指定position处插入</span></span><br><span class="line">    i = <span class="number">0</span></span><br><span class="line">    <span class="keyword">while</span> i &lt; position:</span><br><span class="line">        pre = temp</span><br><span class="line">        temp = temp.next</span><br><span class="line">        i += <span class="number">1</span></span><br><span class="line">    pre.next = new_element</span><br><span class="line">    new_element.next = temp</span><br></pre></td></tr></table></figure>
<h4 id="2-6-删除结点"><a href="#2-6-删除结点" class="headerlink" title="2.6 删除结点"></a>2.6 删除结点</h4><ul>
<li>依然要考虑下标越界问题, 注意此时的此时的上界就不是长度而是长度-1了;<br></li>
<li>删除头结点时, 把老的头结点后边的结点设置为新的头结点, 再把旧的头结点next指向None, 踢出链表<br></li>
<li>删除其他结点时, 先遍历找到到指定位置, 把指定位置前一个结点next指向指定位置后一个结点, 再把指定位置的结点的next指向None, 踢出链表  </li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 删除结点</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">remove</span><span class="params">(self, position)</span>:</span></span><br><span class="line">    <span class="string">"""从任意位置删除一个元素"""</span></span><br><span class="line">    <span class="comment"># 判断下标是否越界</span></span><br><span class="line">    <span class="keyword">if</span> position &lt; <span class="number">0</span> <span class="keyword">or</span> position &gt; self.get_length() - <span class="number">1</span>:</span><br><span class="line">        <span class="keyword">raise</span> IndexError(<span class="string">"删除操作超出索引范围"</span>)</span><br><span class="line">    <span class="comment"># 判断是不是空链表</span></span><br><span class="line">    i = <span class="number">0</span></span><br><span class="line">    temp = self.head</span><br><span class="line">    <span class="keyword">while</span> temp <span class="keyword">is</span> <span class="keyword">not</span> <span class="literal">None</span>:</span><br><span class="line">        <span class="comment"># 删除头结点</span></span><br><span class="line">        <span class="keyword">if</span> position == <span class="number">0</span>:</span><br><span class="line">            <span class="comment"># 新的头结点=旧的头结点的next结点</span></span><br><span class="line">            self.head = temp.next</span><br><span class="line">            <span class="comment"># 旧的头结点指向None, 没有前驱也没有后继, 相当于踢出链表</span></span><br><span class="line">            temp.next = <span class="literal">None</span></span><br><span class="line"></span><br><span class="line">        pre = temp</span><br><span class="line">        <span class="comment"># 遍历链表</span></span><br><span class="line">        temp = temp.next</span><br><span class="line">        i += <span class="number">1</span></span><br><span class="line">        <span class="keyword">if</span> i == position:</span><br><span class="line">            <span class="comment"># temp的前一个结点直接指向temp的后一个结点</span></span><br><span class="line">            pre.next = temp.next</span><br><span class="line">            <span class="comment"># temp也不再指向后一个结点, 而指向None</span></span><br><span class="line">            temp.next = <span class="literal">None</span></span><br><span class="line">            <span class="keyword">return</span></span><br></pre></td></tr></table></figure>
<h4 id="2-7-打印链表"><a href="#2-7-打印链表" class="headerlink" title="2.7 打印链表"></a>2.7 打印链表</h4><p>从头结点开始获取结点中的data值, 打印出来即可</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 打印链表</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">print_list</span><span class="params">(self)</span>:</span></span><br><span class="line">    print(<span class="string">'Linked List:'</span>)</span><br><span class="line">    temp = self.head</span><br><span class="line">    <span class="keyword">while</span> temp <span class="keyword">is</span> <span class="keyword">not</span> <span class="literal">None</span>:</span><br><span class="line">        print(temp.data)</span><br><span class="line">        temp = temp.next</span><br></pre></td></tr></table></figure>
<h4 id="2-8-倒置链表"><a href="#2-8-倒置链表" class="headerlink" title="2.8 倒置链表"></a>2.8 倒置链表</h4><ul>
<li>首先游标指向头结点<br></li>
<li>把头结点next指向None, 让头结点下一个结点指向头结点, 相当把头结点变成了尾结点, 并颠倒了其他所有指针的指向, 完成倒置</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 倒置链表</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">reverse</span><span class="params">(self)</span>:</span></span><br><span class="line">    <span class="string">"""将链表反转过来"""</span></span><br><span class="line">    prev = <span class="literal">None</span></span><br><span class="line">    current = self.head</span><br><span class="line">    <span class="comment"># 头结点指向None, 变成尾结点</span></span><br><span class="line">    <span class="comment"># 第二个结点指向头结点, 以此类推</span></span><br><span class="line">    <span class="keyword">while</span> current:</span><br><span class="line">        next_node = current.next</span><br><span class="line">        current.next = prev  <span class="comment"># None, 旧的第二结点, 旧的第三结点...</span></span><br><span class="line">        prev = current</span><br><span class="line">        current = next_node</span><br><span class="line">    <span class="comment"># 最后遍历的结点(原来的尾结点)设置为头结点</span></span><br><span class="line">    self.head = prev</span><br></pre></td></tr></table></figure>
<h4 id="2-9-把列表-顺序表-转换成链表"><a href="#2-9-把列表-顺序表-转换成链表" class="headerlink" title="2.9 把列表(顺序表)转换成链表"></a>2.9 把列表(顺序表)转换成链表</h4><ul>
<li>首先构造头结点, 把列表的0号元素, 实例化为Node, 并指定为链表的头结点<br></li>
<li>从第二个元素, 也就是下标1开始遍历列表, 不断把列表元素实例化为结点, 同时上一个结点的指针指向当前结点</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 把普通列表转成链表</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">init_list</span><span class="params">(self, data_list)</span>:</span></span><br><span class="line">    <span class="string">"""把传入的list转换成链表"""</span></span><br><span class="line">    <span class="comment"># 调用Node, 把传入列表的第1个元素实例化为链表的头结点</span></span><br><span class="line">    self.head = Node(data_list[<span class="number">0</span>])</span><br><span class="line">    temp = self.head</span><br><span class="line">    <span class="comment"># 从第二个元素开始遍历</span></span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> data_list[<span class="number">1</span>:]:</span><br><span class="line">        node = Node(i)</span><br><span class="line">        <span class="comment"># 上一个结点指向当前结点</span></span><br><span class="line">        temp.next = node</span><br><span class="line">        <span class="comment"># 把当前结点设置为temp</span></span><br><span class="line">        temp = temp.next</span><br></pre></td></tr></table></figure>
    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/blog/tags/%E9%93%BE%E8%A1%A8/" rel="tag"><i class="fa fa-tag"></i> 链表</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/blog/2020/07/01/Python%E5%86%92%E6%B3%A1%E6%8E%92%E5%BA%8F/" rel="prev" title="Python冒泡排序">
      <i class="fa fa-chevron-left"></i> Python冒泡排序
    </a></div>
      <div class="post-nav-item">
    <a href="/blog/2020/07/03/Python%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1%E7%9A%84%E9%97%AE%E4%B8%8E%E7%AD%94/" rel="next" title="Python面向对象的问与答">
      Python面向对象的问与答 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



        </div>
        

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fas fa-yin-yang"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">张雪峰</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/muse/" class="theme-link" rel="noopener" target="_blank">NexT.Muse</a> 强力驱动
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/blog/lib/anime.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.js"></script>
  <script src="/blog/lib/velocity/velocity.min.js"></script>
  <script src="/blog/lib/velocity/velocity.ui.min.js"></script>

<script src="/blog/js/utils.js"></script>

<script src="/blog/js/motion.js"></script>


<script src="/blog/js/schemes/muse.js"></script>


<script src="/blog/js/next-boot.js"></script>


  















  

  

</body>
</html>
